<template>
  <div class="resource-pool-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left-actions">
            <el-checkbox v-model="selectAll" @change="toggleSelectAll">已选中 {{ selectedRowKeys.length }} 项</el-checkbox>
            <el-button size="small" @click="handleGrab">抓取客户</el-button>
            <el-button size="small" @click="handleCall">轮呼</el-button>
            <el-button size="small" @click="handleAddToFollow">添加跟进客户</el-button>
            <el-button size="small" @click="handleAssign">分配客户</el-button>
            <el-button size="small" @click="handleRecycle">回收到公海</el-button>
          </div>
          <div class="right-actions">
            <el-button type="primary" size="small" @click="handleCreate">新建</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选/搜索区域 -->
      <div class="filter-bar">
        <el-input v-model="keyword" placeholder="请输入搜索客户" :prefix-icon="Search" clearable style="width: 240px" @keyup.enter="fetchList" />
        <el-select v-model="advancedFilter" placeholder="高级筛选" clearable style="width: 140px">
          <el-option label="潜在客户" value="潜在客户" />
          <el-option label="意向客户" value="意向客户" />
          <el-option label="需求客户" value="需求客户" />
        </el-select>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 260px" />
        <el-button type="primary" :icon="Search" @click="fetchList">筛选</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 600 }"
        :row-style="{ height: '60px' }"
        :cell-style="{ padding: '12px 0' }"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column prop="customer_name" label="姓名" min-width="160">
          <template #default="{ row }">
            <div class="name-cell">
              <el-avatar :size="28" :src="row.avatar" style="margin-right: 8px" />
              <div class="name-text">{{ row.customer_name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="140">
          <template #default="{ row }">
            <span>{{ row.phone || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="客户类型" width="110">
          <template #default="{ row }">
            <el-tag size="small" :type="mapTypeToTag(row.type).type">{{ mapTypeToTag(row.type).text }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assistStage" label="助贷阶段" width="120" />
        <el-table-column prop="customer_level" label="AI意向等级" width="120" />
        <el-table-column prop="expected_amount" label="期望金额" width="120" />
        <el-table-column prop="customer_situation" label="客户情况" min-width="200" show-overflow-tooltip />
        <el-table-column prop="source" label="信息来源" width="160" />
        <el-table-column prop="salesman_id" label="营销专员" width="140" />
        <el-table-column prop="tags" label="客户标签" min-width="160">
          <template #default="{ row }">
            <div class="tags-cell">
              <el-tag v-for="t in parseTags(row.tags)" :key="t" size="small" class="tag-item">{{ t }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="call_status" label="轮呼状态" width="120">
          <template #default="{ row }">
            <el-tag 
              size="small" 
              :type="getCallStatusType(row.call_status)"
            >
              {{ getCallStatusText(row.call_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              text 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              text 
              @click="handleView(row)"
            >
              查看
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { userInfo, isLoggedIn } from '@/utils/userStore'

const router = useRouter()
const tableRef = ref()
const keyword = ref('')
const advancedFilter = ref('')
const dateRange = ref<[Date, Date] | null>(null)

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const tableData = ref<any[]>([])
const selectedRowKeys = ref<string[]>([])
const selectAll = ref(false)

// 将客户类型数字转换为文本
const mapTypeToTag = (type: number) => {
  switch (type) {
    case 1:
      return { type: 'success', text: '潜在客户' }
    case 2:
      return { type: 'warning', text: '意向客户' }
    case 3:
      return { type: 'info', text: '需求客户' }
    case 4:
      return { type: 'primary', text: '签单客户' }
    case 5:
      return { type: 'danger', text: '放款客户' }
    default:
      return { type: 'info', text: '未知类型' }
  }
}

// 轮呼状态相关函数 - 修改为处理数字状态
const getCallStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    case 4:
      return 'danger'
    default:
      return 'info'
  }
}

const getCallStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '未轮呼'
    case 2:
      return '轮呼中'
    case 3:
      return '已接通'
    case 4:
      return '未接通'
    default:
      return '未知状态'
  }
}

// 解析标签字符串为数组
const parseTags = (tags: string) => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return tags.split(',').filter(t => t.trim())
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  if (isNaN(date.getTime())) return ''
  return date.toLocaleString()
}

const fetchList = async () => {
  try {
    // 构建查询参数
    const params = {
      page: page.value,
      page_size: pageSize.value,
      keyword: keyword.value || undefined,
      // 根据需要添加其他筛选条件
      type: advancedFilter.value ? {
        '潜在客户': 1,
        '意向客户': 2,
        '需求客户': 3
      }[advancedFilter.value] : undefined
    }
    
    // 发送请求到后端接口，这里使用跟进客户接口
    const response = await axios.get('/customers/following', { params })
    
    if (response.data.data && Array.isArray(response.data.data.customers)) {
      tableData.value = response.data.data.customers
      // 尝试多种可能的total值位置，确保分页功能正常
      total.value = response.data.total || response.data.data.total || tableData.value.length
    } else {
      // 兜底处理，确保tableData始终是数组
      console.warn('API响应数据结构不符合预期', response.data)
      tableData.value = []
      total.value = 0
    }
    
    console.log('获取跟进客户列表成功，共', total.value, '条数据')
  } catch (error: any) {
    console.error('获取跟进客户列表失败:', error)
    // 区分网络错误和服务器错误
    if (error.response) {
      // 服务器返回错误
      const errorMsg = error.response.data?.message || `获取跟进客户列表失败: ${error.response.status}`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      // 请求发出但无响应
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      // 其他错误
      ElMessage.error('获取跟进客户列表失败，请稍后重试')
    }
    tableData.value = []
    total.value = 0
  }
}

const resetFilters = () => {
  keyword.value = ''
  advancedFilter.value = ''
  dateRange.value = null
  page.value = 1
  fetchList()
}

const onPageChange = (p: number) => {
  page.value = p
  fetchList()
}

const onSizeChange = (s: number) => {
  pageSize.value = s
  page.value = 1
  fetchList()
}

const onSelectionChange = (rows: any[]) => {
  selectedRowKeys.value = rows.map(r => r.customer_id)
  selectAll.value = selectedRowKeys.value.length === tableData.value.length && tableData.value.length > 0
}

const toggleSelectAll = () => {
  if (!tableRef.value) return
  if (selectAll.value) {
    tableRef.value.clearSelection()
    tableData.value.forEach((row: any) => tableRef.value.toggleRowSelection(row, true))
    // 确保selectedRowKeys使用customer_id
    selectedRowKeys.value = tableData.value.map(r => r.customer_id)
  } else {
    tableRef.value.clearSelection()
    selectedRowKeys.value = []
  }
}

// 轮呼功能相关接口类型定义
interface AndroidAppMQMessage {
  phone: string
  device_id: string
  description?: string
  name?: string
  time: string
}

// 轮呼功能实现
const handleCall = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要轮呼的客户')
    return
  }

  try {
    // 获取选中的客户数据
    const selectedCustomers = tableData.value.filter(row => 
      selectedRowKeys.value.includes(row.customer_id)
    )

    // 获取当前用户信息，确保有有效的device_id
    const currentUser = userInfo || {}
    const username = currentUser.username || localStorage.getItem('username') || 'unknown_user'
    
    // 构建轮呼消息数据
    const mqMessages: AndroidAppMQMessage[] = selectedCustomers.map(customer => ({
      phone: customer.phone,
      device_id: username, // 使用当前登录用户名作为device_id
      description: customer.customer_situation, // 客户情况作为描述
      name: customer.customer_name, // 客户姓名
      time: new Date().toISOString()
    }))

    // 根据选择数量决定调用单个还是批量接口
    if (selectedCustomers.length === 1) {
      // 单个客户轮呼
      await axios.post('/rabbitmq/product', mqMessages[0])
      ElMessage.success(`已启动对客户 ${selectedCustomers[0].customer_name} 的轮呼`)
    } else {
      // 批量客户轮呼
      await axios.post('/rabbitmq/product_batch', mqMessages)
      ElMessage.success(`已启动对 ${selectedCustomers.length} 个客户的批量轮呼`)
    }

    // 更新选中客户的轮呼状态
    selectedCustomers.forEach(customer => {
      customer.call_status = 2 // 2表示轮呼中
    })

    // 清空选择
    selectedRowKeys.value = []
    selectAll.value = false
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }

  } catch (error) {
    console.error('轮呼启动失败:', error)
    ElMessage.error('轮呼启动失败，请稍后重试')
  }
}

const handleCreate = () => {
  ElMessage.info('新建客户功能待实现')
}

const handleGrab = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要抓取的客户')
    return
  }
  ElMessage.info(`抓取客户功能待实现，已选择 ${selectedRowKeys.value.length} 个客户`)
}

const handleAssign = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要分配的客户')
    return
  }
  ElMessage.info(`分配客户功能待实现，已选择 ${selectedRowKeys.value.length} 个客户`)
}

const handleRecycle = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要回收的客户')
    return
  }
  ElMessageBox.confirm('确定要将选中的客户回收到公海吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`已回收 ${selectedRowKeys.value.length} 个客户到公海`)
    selectedRowKeys.value = []
    selectAll.value = false
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
  }).catch(() => {})
}

// 添加到跟进客户
const handleAddToFollow = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要添加到跟进的客户')
    return
  }
  ElMessage.info(`添加跟进客户功能待实现，已选择 ${selectedRowKeys.value.length} 个客户`)
}

// 编辑客户
const handleEdit = (row: any) => {
  ElMessage.info(`编辑客户：${row.customer_name}`)
  // 这里可以添加编辑客户的逻辑，比如打开编辑对话框或跳转到编辑页面
  console.log('编辑客户信息:', row)
}

// 查看客户详情
const handleView = (row: any) => {
  // 导航到客户详情页面
  // 使用customer_id或id作为主键
  const customerId = row.customer_id || row.id
  if (customerId) {
    router.push(`/customers/detail/${customerId}`)
  } else {
    ElMessage.error('客户ID不存在，无法查看详情')
  }
}

// 发送短信功能
const handleSendSms = (row: any) => {
  // 检查客户是否有手机号
  if (!row.phone) {
    ElMessage.warning('该客户没有手机号，无法发送短信')
    return
  }
  
  // 显示发送短信对话框
  ElMessageBox.prompt('请输入要发送的短信内容', '发送短信', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入短信内容',
    showClose: false,
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        const messageContent = instance.content
        
        if (!messageContent || messageContent.trim() === '') {
          ElMessage.warning('请输入短信内容')
          instance.validate().then(() => {
            done()
          }).catch(() => {
            done()
          })
          return
        }
        
        try {
          // 这里可以调用短信发送API
          console.log('发送短信到:', row.phone, '内容:', messageContent)
          
          // 模拟API调用
          // await axios.post('/sms/send', {
          //   phone: row.phone,
          //   content: messageContent,
          //   customerId: row.customer_id || row.id
          // })
          
          ElMessage.success('短信发送成功')
          done()
        } catch (error) {
          console.error('短信发送失败:', error)
          ElMessage.error('短信发送失败，请稍后重试')
          done()
        }
      } else {
        done()
      }
    }
  }).catch(() => {
    // 用户取消操作
  })
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped lang="scss">
.resource-pool-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .left-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .right-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .filter-bar {
    display: flex;
    gap: 12px;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
  }

  .name-cell {
    display: flex;
    align-items: center;
  }

  .name-text {
    font-weight: 600;
  }

  .customer-id {
    margin-left: 8px;
    color: #909399;
    font-size: 12px;
  }

  .tags-cell {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
  }

  .tag-item {
    margin: 0;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0 4px;
  }
}
</style>
